package com.example.service;

import com.example.model.dto.UserProfileDTO;
import com.example.model.entity.User;
import com.example.repository.UserRepository;
import com.example.repository.FollowRepository;
import com.example.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;


@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private FollowRepository followRepository;
    
    @Autowired
    private LikeRepository likeRepository;

    public User register(User user) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User findById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    @Transactional
    public User updateUser(Long id, User userDetails) {
        User user = findById(id);
        user.setNickname(userDetails.getNickname());
        user.setAvatar(userDetails.getAvatar());
        user.setDescription(userDetails.getDescription());
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }

    public UserDetails loadUserByUsername(String username) {
        User user = findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                new ArrayList<>()
        );
    }

    public UserProfileDTO getUserProfile() {
        // 获取当前登录用户的用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = findByUsername(username);
        
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        UserProfileDTO profileDTO = new UserProfileDTO();
        profileDTO.setUserId(user.getId().toString());
        profileDTO.setNickname(user.getNickname());
        profileDTO.setAvatar(user.getAvatar());
        profileDTO.setBio(user.getDescription());
        profileDTO.setLocation(user.getLocation());
        
        // 获取关注数
        long followingsCount = followRepository.countByFollowerId(user.getId());
        profileDTO.setFollowings((int) followingsCount);
        
        // 获取粉丝数
        long followersCount = followRepository.countByFollowingId(user.getId());
        profileDTO.setFollowers((int) followersCount);
        
        // 获取获赞数
        long likesCount = likeRepository.countByUserId(user.getId());
        profileDTO.setLikes((int) likesCount);

        return profileDTO;
    }
} 